package cn.itcast.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
 *Author:TH
 *Dete:2019/10/2916:11
 */
public class UserService implements UserDetailsService{

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    //模拟数据库中的用户数据
    public static Map<String, Map> map = new HashMap<>();

    //初始化用户数据
    public void initData() {
        Map<String, String> user1 = new HashMap();
        user1.put("username", "admin");
        user1.put("password", passwordEncoder.encode("1234"));

        Map<String, String> user2 = new HashMap();
        user2.put("username", "zhangsan");
        user2.put("password", passwordEncoder.encode("1234"));

        map.put(user1.get("username"), user1);
        map.put(user2.get("username"), user2);
    }

    //根据用户名查询用户信息
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        initData();
        System.out.println("username:" + username);

        Map<String, String> userInDb = map.get(username);//模拟根据用户名查询数据库
        if (userInDb == null) {
            //根据用户名没有查询到用户
            return null;
        }
        //模拟数据库中的密码，后期需要查询数据库
        String passwordInDb = userInDb.get("password");

        List<GrantedAuthority> list = new ArrayList<>();
        //授权，后期需要改为查询数据库动态获得用户拥有的权限和角色
        if (username.equals("admin")){
            list.add(new SimpleGrantedAuthority("add"));
            list.add(new SimpleGrantedAuthority("delete"));
        }
        list.add(new SimpleGrantedAuthority("ROLE_ADMIN"));

        UserDetails user = new User(username, passwordInDb, list);
        return user;
    }
}
